package ui.panels.primary.players;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.ListModel;

import org.apache.log4j.Logger;

import auxiliary.AuxiliaryClass;

import ui.flowManager.FlowManagerImpl;
import ui.flowManager.expirimentProperties.ExperimentProperties;
import ui.flowManager.expirimentProperties.GameRepresentation;
import ui.flowManager.expirimentProperties.ExperimentProperties.Agent_Group;
import ui.panels.commands.OpenPlayerPropsCommand;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
/**
 * @author vladimir && alon
 *
 *	The panel Show table of Players
 */
public class PlayersPanel extends JPanel{
	
	private JLabel 					jLabel1;
	private JLabel 					numPlayerLabel;

	private JButton 				jButton1;	
	private JButton 				addPlayersButton;

	private JTextField 				morePlayersField;
	private JTextField 				numPlayersField;
	
	private	JList<String> 			 list;
	private JScrollPane 				pane;
	private	DefaultListModel<String> listModel;
	

	private int 					gameNumber = 0;
	private int 					numberOfPlayers = 0;
	private final Agent_Group		group = Agent_Group.CONTROL_AGENT;
	Logger log = Logger.getLogger(this.getClass());
	
	/*** Set a special look for the window*/
	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * Default CTOR
	 */
	public PlayersPanel ()
	{
		super();
	}
	
	/**
	 * @param numberGame
	 * 
	 * CTOR that will create list of players from Experiment Properties
	 */
	public PlayersPanel (int gameNumber)
	{
		super();
		this.gameNumber = gameNumber;
		
	}
	
	/**
	 * @param props 
	 */
	public void show(ExperimentProperties props) {
		
		try {
			GroupLayout thisLayout = new GroupLayout((JComponent)this);
			this.setLayout(thisLayout);
			setPreferredSize(new Dimension(200, 480));
			
			listModel = new DefaultListModel<String>();
			list = new JList<String>(listModel);
			pane = new JScrollPane(list);
			
			{
				morePlayersField = new JTextField();
			}
			{
				addPlayersButton = new JButton("+");
				addPlayersButton.setFont(new Font(Font.SERIF, Font.BOLD, 22));
				addPlayersButton.setForeground(Color.MAGENTA);
			}

			{
				jLabel1 = new JLabel("Control Agents", JLabel.CENTER);
				jLabel1.setFont(new Font("Serif", Font.BOLD, 15));
				
			}
			{
				numPlayerLabel = new JLabel("Enter number of players");
			}
			{
				
			}

			{
				numPlayersField = new JTextField("");
			}
			{
				jButton1 = new JButton();
				jButton1.setText("Enter");
			}
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.addContainerGap(49, 49)
				.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE)
				.addComponent(numPlayerLabel, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
				.addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(jButton1, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE)
				    .addComponent(numPlayersField, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE))
				.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
				.addComponent(pane, 0, 251, Short.MAX_VALUE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
				.addGroup(thisLayout.createParallelGroup()
				    .addComponent(addPlayersButton, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
				    .addComponent(morePlayersField, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE))
				.addContainerGap(33, 33));
			thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
				.addContainerGap(12, 12)
				.addGroup(thisLayout.createParallelGroup()
				    .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				        .addComponent(numPlayerLabel, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE)
				        .addGap(0, 18, Short.MAX_VALUE))
				    .addGroup(thisLayout.createSequentialGroup()
				        .addPreferredGap(numPlayerLabel, morePlayersField, LayoutStyle.ComponentPlacement.INDENT)
				        .addGroup(thisLayout.createParallelGroup()
				            .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				                .addComponent(morePlayersField, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE)
				                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				                .addComponent(addPlayersButton, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
				                .addGap(0, 19, Short.MAX_VALUE))
				            .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				                .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 142, GroupLayout.PREFERRED_SIZE)
				                .addGap(0, 20, Short.MAX_VALUE))
				            .addGroup(thisLayout.createSequentialGroup()
				                .addPreferredGap(morePlayersField, numPlayersField, LayoutStyle.ComponentPlacement.INDENT)
				                .addGroup(thisLayout.createParallelGroup()
				                    .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				                        .addComponent(numPlayersField, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE)
				                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				                        .addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)
				                        .addGap(0, 0, Short.MAX_VALUE))
				                    .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				                        .addComponent(pane, 0, 150, Short.MAX_VALUE)
				                        .addGap(0, 6, GroupLayout.PREFERRED_SIZE)))))))
				.addContainerGap(20, 20));

			//set the listeners
			setListeners(props);
			//case the game is not default, call to set the players in the list
			if(isAttachedToGame())
			{
				setPlayersFromProperties(props);
			}
			
		} catch (Exception e) {
			log.debug(e.toString());
		}
		
	}

	
	/**
	 * 
	 */
	public void setGameLabel(int gameNumber)
	{
		jLabel1.setText("Game "+ gameNumber);
	}
	
	/**
	 * 
	 * @param props
	 */
	public void setPlayersFromProperties(ExperimentProperties props)
	{
		//case this game have already players
		if(props.havePlayers(gameNumber, group) == true)
		{
			//set the list of players
			setPlayers(props.getNumOfPlayers(gameNumber, group));
		}
	}


	/**
	 * @param numPlayers
	 */
	public void setPlayers(int numPlayers)
	{
		//update the current number 
		numberOfPlayers = 0;
		//add the Players to the list
		addPlayers(numPlayers);
	}	
	
	public void addPlayers(int numPlayers)
	{
		//add the Players to the list
		for(int i = 0; i < numPlayers; ++i)
		{
			//add to the list 
			listModel.add(i + this.numberOfPlayers, "Player " + (i + this.numberOfPlayers + 1));
		}
		//update the number of players in the game
		this.numberOfPlayers = this.numberOfPlayers + numPlayers;
	}	
	
	
	
	public DefaultListModel<String> getListModel() {
		return listModel;
	}

	public int getGameNumber() {
		return gameNumber;
	}

	
	public JList<String> getList() {
		return list;
	}
	
	/**
	 * Update the UI of the list:
	 * 			Delete the player from the list
	 * 			Update the rest players index
	 */
	public void setTheListUI(int playerNumber, ExperimentProperties props)
	{		
		int index = playerNumber - 1;
		//remove from list - the UI
		listModel.remove(index);
		//check how many players exist after that player
		int players = props.getGame(gameNumber).getNumOfPlayers(group);
		players = players - playerNumber;
		//update the next players index
		for (int i = 0; i < players; ++i)
		{
			listModel.set(index, "Player " + (++index));
		}

		//update this panel
		this.numberOfPlayers--;
	}
	
	public void removeFromProperties(int playerNumber, ExperimentProperties props)
	{
		GameRepresentation game = props.getGame(gameNumber);
		//FlowManagerImpl.getInstance().emptyProperties();
		game.removePlayer(playerNumber, group);	
	}

	/**
	 * @return
	 */
	private boolean isAttachedToGame()
	{
		return (gameNumber > 0);
	}
	
	
	private void setListeners(final ExperimentProperties props)
	{
		// set the list for double click and left click
		list.addMouseListener(new MouseJListener(this, props));
		list.addKeyListener(new KeyJList(this, list, props));
		
		//set the buttons
		ActionListener actionListener = createActionListener(props);
		jButton1.addActionListener(actionListener);
		addPlayersButton.addActionListener(actionListener);
		
	}
	//end setListeners
	
	
	private ActionListener createActionListener(final ExperimentProperties props)
	{
		ActionListener actionListener = new ActionListener() {
			
			public void actionPerformed(ActionEvent event) {
				//case it is initialize the game (Enter)
				if(event.getSource() ==  jButton1)
				{
					String inputPlayers = numPlayersField.getText();
					
					//case not attached to a game
					if(gameNumber == 0)
					{
						return;
					}
					
					//case not empty and is a number in both fields
					if((!inputPlayers.equals("")) && 
						 (AuxiliaryClass.isNumber(inputPlayers)) )
					{
						int numberPlayers = Integer.parseInt(inputPlayers);
						// update properties
						props.setPlayers(gameNumber, numberPlayers, group);						
						//empty the player list
						listModel.removeAllElements();
						//add the players to the list
						setPlayers(numberPlayers);
					}	
				}
				
				//case it is adding players
				else if(event.getSource() == addPlayersButton)
				{
					//case the game not initialized 
					if((gameNumber == 0) ||(!props.isInitialized(gameNumber)))
					{
						return;
					}
					
					String morePlayersStr = morePlayersField.getText();
					
					//case it is not number
					if (!AuxiliaryClass.isNumber(morePlayersStr))
						return;
					
					int morePlayers = Integer.parseInt(morePlayersStr);
					//add the players to the ExperementPropeties
					props.addPlayers(gameNumber, morePlayers, group);
					//add the players to the list (GUI)
					addPlayers(morePlayers);			
				}
			}
			
		};
		
		return actionListener;
	}
	
	public void executeListGame(JList jlist, int playerNumber)
	{
	     ListModel dlm = jlist.getModel();
	     Object item = dlm.getElementAt(playerNumber - 1);
	     jlist.ensureIndexIsVisible(playerNumber - 1);


	     //execute the OpenPlayerPropsCommand
	     OpenPlayerPropsCommand openPlayerPropsCommand = new OpenPlayerPropsCommand();
	     openPlayerPropsCommand.setPlayerNumber(playerNumber);
	     openPlayerPropsCommand.setGameNumber(gameNumber);
	     openPlayerPropsCommand.setGroup(group);
	     openPlayerPropsCommand.execute();
	}
	
}
